package cn.com.xy.sms.sdk.service.updateservice;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.XyHttpRunnable;
import cn.com.xy.sms.sdk.util.FileUtils;
import cn.com.xy.sms.sdk.util.JarSubCheckQueue;
import cn.com.xy.sms.sdk.util.KeyManager;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.util.ParseManager;

public class UpdateService extends IntentService {

    public static long sFirstStartDelay = Constant.MINUTE;
    public static final String ACTION = "cn.com.xy.sms.sdk.service.updateservice.UpdateService";
    static boolean isSetAlarm = false;

    static boolean isInitSysparam = false;
    static Map<String, String> extend = new HashMap<String, String>();
    static String channel = null;
    static String simIccid = null;
    static boolean preLoadEnable = false;
    static boolean smsLocateEnable = false;
    /*SDK-758 songzhirong 20170410 start*/
    static PendingIntent sender;
    /*SDK-758 songzhirong 20170410 end*/

    public UpdateService(String name) {
        super(name);
        // TODO Auto-generated constructor stub
    }

    public UpdateService() {
        super("UpdateService");
        LogManager.i("xiaoyuan", "updateService UpdateService");

    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogManager.i("xiaoyuan", "updateService onCreate");

    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        LogManager.i("xiaoyuan", "updateService onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    boolean setSysparamAndInit(Intent serviceIntent) throws Exception {
        try {
            boolean isReboot = serviceIntent.getExtras().getBoolean("isReboot", false);
            if (Constant.getContext() == null) {
                Constant.initContext(UpdateService.this);
            }
            boolean isFistInstall = isFistInstall(UpdateService.this);// 假如files下没有jar包，说明清除了数据
            if (StringUtils.isNull(KeyManager.channel) || StringUtils.isNull(XyHttpRunnable.appKeySign)
                    || isFistInstall) {
                initSysparam(serviceIntent);// 设置参数
                if (isReboot) {
                    LogManager.i("xiaoyuan", "是重启，只初始化基本参数，并设置JobScheduler");
                    KeyManager.initAppKey();
                    ParseManager.startJobScheduler(UpdateService.this,extend);
                } else {
                    LogManager.i("xiaoyuan", "不是重启，初始化sdk，Service中启动的，不用重复启动Service");
                    extend.put(Constant.START_SERVICE, "false");
                    ParseManager.initSdk(UpdateService.this, channel, simIccid, preLoadEnable, smsLocateEnable, extend);
                    return true;
                }
            }else{
                ParseManager.startJobScheduler(UpdateService.this,extend);
            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "UpdateService handleTask" + e.getLocalizedMessage(), e);
        }
        return false;
    }

    void checkAndDoTask() {
        if (isFistInstall(UpdateService.this)) {
            return;
        }
        long time = SysParamEntityManager.getLongParam(Constant.ALGORITHM_UPDATE_TIME, -1, Constant.getContext());
        long cyc = SysParamEntityManager.getLongParam(Constant.CONFIG_UPDATE_CYC, 720 * Constant.MINUTE,
                Constant.getContext());
        long now = System.currentTimeMillis();

        LogManager.i("xiaoyuan", "UpdateService time=" + time + " cyc=" + cyc + " now=" + now);

        if (time != -1 && now - time > cyc) {
            LogManager.i("xiaoyuan", "UpdateService 符合条件，马上更新");

            updateNow();
        }

    }

    void checkAndSetAlarm(Intent serviceIntent) {
        if (isSetAlarm) {
            return;
        }

        long time = SysParamEntityManager.getLongParam(Constant.ALGORITHM_UPDATE_TIME, -1, Constant.getContext());
        long cyc = SysParamEntityManager.getLongParam(Constant.CONFIG_UPDATE_CYC, 720 * Constant.MINUTE,
                Constant.getContext());
        if (time == -1) {
            SysParamEntityManager.setParam(Constant.ALGORITHM_UPDATE_TIME,
                    (String.valueOf(System.currentTimeMillis() + UpdateService.sFirstStartDelay)));
            LogManager.i("xiaoyuan", "首次启动UpdateService 设置启动时间，并启动Alar " + UpdateService.sFirstStartDelay + " 后执行更新");

        }
        /*SDK-758 songzhirong 20170410 start*/
        sender = PendingIntent.getService(UpdateService.this, 0, getIntent(UpdateService.this),
                PendingIntent.FLAG_UPDATE_CURRENT);
        /*SDK-758 songzhirong 20170410 end*/
        // 开始时间
        AlarmManager am = (AlarmManager) UpdateService.this.getSystemService(ALARM_SERVICE);

        long realtime = SystemClock.elapsedRealtime();

        am.setRepeating(AlarmManager.ELAPSED_REALTIME, realtime + UpdateService.sFirstStartDelay, cyc, sender);

        isSetAlarm = true;

        LogManager.i("xiaoyuan", "UpdateService 首次执行时间" + UpdateService.sFirstStartDelay + " 后，周期" + (cyc));

    }

    // 设置UpdateService，内部启动，需要设置isReboot参数为false
    public static Intent getIntent(Context context) {
        Intent intent = new Intent(context, UpdateService.class);
        intent.putExtra("isReboot", false);
        return intent;
    }

    public void handleTask(Intent serviceIntent) {
        try {
            boolean isCallInitsdk = setSysparamAndInit(serviceIntent);
            if (!isCallInitsdk) {
                checkAndDoTask();// 假如调用了初始化的函数，没有必要调用检查更新
            }
            checkAndSetAlarm(serviceIntent);// 设置闹钟，只设置一次

        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "UpdateService handleTask" + e.getLocalizedMessage(), e);
        }
    }

    public static void updateNow() {
        JarSubCheckQueue.checkJarsUpdate(true, false);
        SysParamEntityManager.setParam(Constant.ALGORITHM_UPDATE_TIME, String.valueOf(System.currentTimeMillis()));
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        handleTask(intent);

    }

    static boolean isFistInstall(Context context) {
        if (Constant.getContext() == null) {
            Constant.initContext(context);
        }
        List<File> listFile = FileUtils.getFileList(Constant.getPARSE_PATH(), "PU", ".jar");
        boolean isFistInstll = (listFile == null || listFile.size() <= 0);
        return isFistInstll;
    }

    void initSysparam(Intent serviceIntent) throws Exception {
        if (isInitSysparam) {
            // 只设置一次，因为闹钟启动的service的intent已经不带有下面这些参数
            return;
        }
        String[] values = (String[]) serviceIntent.getExtras().get("extend");
        if (values == null || values.length % 2 != 0) {
            throw new Exception("extend is null or len %2 !=0");
        }

        channel = serviceIntent.getExtras().getString("channel");
        simIccid = serviceIntent.getExtras().getString("simIccid");
        preLoadEnable = serviceIntent.getExtras().getBoolean("preLoadEnable");
        smsLocateEnable = serviceIntent.getExtras().getBoolean("smsLocateEnable"); 

        /*HUAWEICARD-663 songzhirong 20170322 start*/
        for (int i = 0; i < values.length; i += 2) {       
            extend.put(values[i], values[i + 1]);          
        }        
        SysParamEntityManager.initParams(UpdateService.this, channel, simIccid, preLoadEnable, smsLocateEnable, extend);
        /*HUAWEICARD-663 songzhirong 20170322 end*/
        isInitSysparam = true;
    }
    /*SDK-758 songzhirong 20170410 start*/
    public static void cancelUpdateService(Context context){
    	try {
    		if(context == null){
    			return;
    		}
    		isSetAlarm = false;
    		if(sender!=null){
    	        AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
    	        am.cancel(sender);
    	        LogManager.d("xiaoyuan", "cancelUpdateService sender="+sender);
    		}
			
		} catch (Throwable e) {
			LogManager.e(Constant.TAG, " cancelUpdateService error"+e.getLocalizedMessage(), e);
		}
    }
    /*SDK-758 songzhirong 20170410 end*/
}
